package controllers

import (
	"database/sql"
	"encoding/json"
	"fmt"
	"net/http"
	// "test/model"
	// "strconv"
	_ "test/mysql"
)

type Item struct {
	Uid        int    `json:uid`
	Username   string `json:username`
	Uepartment string `json:department`
	Ureated    string `json:created`
}
type Grid struct {
	// Total int    `json:total`
	Status int    `json:status`
	Info   string `json:info`
	Msg    []Item `json:product`
}

/*
*return a json file
 */

func IndexController(w http.ResponseWriter, r *http.Request) {
	// w.Header().Set("Access-Control-Allow-Origin", "*")
	// w.Header().Add("Access-Control-Allow-Headers", "Content-Type")
	// w.Header().Set("content-type", "application/json")
	// myJson = model.Query()
	db, err := sql.Open("mysql", "root:123456@tcp(192.168.1.243:3306)/xuexi?charset=utf8")
	checkErr(err)

	query, _ := db.Query("SELECT * FROM userinfo")
	column, _ := query.Columns()              //读出查询出的列字段名
	values := make([][]byte, len(column))     //values是每个列的值，这里获取到byte里
	scans := make([]interface{}, len(column)) //因为每次查询出来的列是不定长的，用len(column)定住当次查询的长度
	for i := range values {                   //让每一行数据都填充到[][]byte里面
		scans[i] = &values[i]
	}
	i := 0
	var m Grid
	m.Status = 0
	m.Info = "ok"
	for query.Next() { //循环，让游标往下移动
		var uid int
		var username string
		var department string
		var created string
		if err := query.Scan(scans...); err != nil { //query.Scan查询出来的不定长值放到scans[i] = &values[i],也就是每行都放在values里
			fmt.Println(err)
			return
		}
		err = query.Scan(&uid, &username, &department, &created)
		checkErr(err)
		orderi := Item{Uid: uid, Username: username, Uepartment: department, Ureated: created}
		fmt.Println(orderi)
		m.Msg = append(m.Msg, orderi)
		i++
	}
	db.Close()
	bytes, _ := json.Marshal(m)
	fmt.Printf("json:m,%s\n", bytes)
	w.WriteHeader(http.StatusOK)
	w.Write(bytes)

}

func checkErr(err error) {
	if err != nil {
		panic(err)
	}
}
